/**
 * Created by zoushuiyun on 2017/7/25.
 */
import { Injectable } from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
} from '@angular/router';
import { CacheService } from '@core/routes-services/cache.service';
import { myValidNull } from '@core/util/string-utils';

/**
 * 权限路由守卫
 */
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private cacheService: CacheService, private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const url: string = state.url;

    return this.checkLogin(url);
  }

  /**
   * 验证是否登录 有用户相关缓存信息，否则跳转至登录页
   *
   * @param url
   * @returns {boolean}
   */
  checkLogin(url: string): boolean {
    const token: any = this.cacheService.getTokenInfo();
    // 登录 B 端
    if (!myValidNull(token)) {
      return true;
    }
    // Navigate to the login page with extras
    console.log('===未登录，或缓存过期，重新登录===')
    this.router.navigate(['/passport/login']);
    return false;
  }

}
